<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<!-- 查询表单区域 -->
			<el-row v-show="showSearch">
				<el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList">
					<el-form-item label="设备sn" prop="deviceSn">
						<el-input placeholder="请输入设备sn" v-model="state.queryForm.deviceSn" />
					</el-form-item>
					<el-form-item label="上报时间" prop="gpsTime">
						<el-date-picker
							type="datetimerange"
							start-placeholder="请选择开始时间"
							end-placeholder="请选择结束时间"
							v-model="state.queryForm.gpsTime"
							value-format="YYYY-MM-DD HH:mm:ss"
						/>
					</el-form-item>
					<el-form-item label="报警等级" prop="alarmLevel">
						<el-input placeholder="请输入报警等级" v-model="state.queryForm.alarmLevel" />
					</el-form-item>
					<el-form-item label="报警电流类型" prop="alarmType">
						<el-select placeholder="请选择报警电流类型" v-model="state.queryForm.alarmType" clearable>
							<el-option label="泄露电流" value="1" />
							<el-option label="工作电流" value="2" />
							<el-option label="接地电流" value="3" />
						</el-select>
					</el-form-item>
					<el-form-item label="报警状态" prop="alarmStatus">
						<el-select placeholder="请选择报警状态" v-model="state.queryForm.alarmStatus" clearable>
							<el-option label="未处理" value="0" />
							<el-option label="已处理" value="1" />
						</el-select>
					</el-form-item>
					<el-form-item label="处理时间" prop="resolvedTime">
						<el-date-picker
							type="datetimerange"
							start-placeholder="请选择开始时间"
							end-placeholder="请选择结束时间"
							v-model="state.queryForm.resolvedTime"
							value-format="YYYY-MM-DD HH:mm:ss"
						/>
					</el-form-item>
					<el-form-item label="报警内容" prop="alarmContent">
						<el-input placeholder="请输入报警内容" v-model="state.queryForm.alarmContent" />
					</el-form-item>
					<el-form-item>
						<el-button icon="search" type="primary" @click="getDataList"> 查询 </el-button>
						<el-button icon="Refresh" @click="resetQuery">重置</el-button>
					</el-form-item>
				</el-form>
			</el-row>

			<!-- 操作按钮区域 -->
			<el-row>
				<div class="mb8" style="width: 100%">
					<el-button icon="folder-add" type="primary" class="ml10" @click="formDialogRef.openDialog()" v-auth="'admin_deviceAlarm_add'">
						新增
					</el-button>
					<el-button plain icon="upload-filled" type="primary" class="ml10" @click="excelUploadRef.show()" v-auth="'admin_deviceAlarm_add'">
						导入
					</el-button>
					<el-button plain :disabled="multiple" icon="Delete" type="primary" v-auth="'admin_deviceAlarm_del'" @click="handleDelete(selectObjs)">
						删除
					</el-button>
					<right-toolbar
						v-model:showSearch="showSearch"
						:export="'admin_deviceAlarm_export'"
						@exportExcel="exportExcel"
						class="ml10 mr20"
						style="float: right"
						@queryTable="getDataList"
					/>
				</div>
			</el-row>

			<!-- 数据表格区域 -->
			<el-table
				:data="state.dataList"
				v-loading="state.loading"
				border
				:cell-style="tableStyle.cellStyle"
				:header-cell-style="tableStyle.headerCellStyle"
				@selection-change="selectionChangHandle"
				@sort-change="sortChangeHandle"
			>
				<el-table-column type="selection" width="40" align="center" />
				<el-table-column type="index" label="#" width="50" />
				<el-table-column prop="deviceSn" label="设备sn" show-overflow-tooltip />
				<el-table-column prop="gpsTime" label="上报时间" show-overflow-tooltip />
				<el-table-column width="110" prop="alarmType" label="报警电流类型">
					<template #default="{ row }">
						<el-tag v-if="row.alarmType == 1">泄露电流</el-tag>
						<el-tag v-else-if="row.alarmType == 2">工作电流</el-tag>
						<el-tag v-else-if="row.alarmType == 3">接地电流</el-tag>
						<el-tag v-else>未知</el-tag>
					</template>
				</el-table-column>
				<el-table-column width="90" prop="alarmLevel" label="报警等级" show-overflow-tooltip />
				<el-table-column width="90" prop="alarmValue" label="电流值" show-overflow-tooltip />
				<el-table-column width="100" prop="alarmStatus" label="报警状态" show-overflow-tooltip>
					<template #default="{ row }">
						<el-tag v-if="row.alarmStatus == 0" type="danger">未处理</el-tag>
						<el-tag v-else-if="row.alarmStatus == 1" type="success">已处理</el-tag>
						<el-tag v-else>未知</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="resolvedTime" label="处理时间" show-overflow-tooltip />
				<el-table-column prop="resolvedRemark" label="处理备注" show-overflow-tooltip />
				<el-table-column width="90" prop="unit" label="测量单位" show-overflow-tooltip>
					<template #default="{ row }">
						<el-tag v-if="row.unit == 1">A</el-tag>
						<el-tag v-else-if="row.unit == 2">uA</el-tag>
						<el-tag v-else-if="row.unit == 3">mA</el-tag>
						<el-tag v-else>未知</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="alarmContent" label="报警内容" show-overflow-tooltip />
				<el-table-column width="90" prop="action" label="操作">
					<template #default="{ row }">
						<el-button v-if="row.alarmStatus == 0" text type="primary"  v-auth="'admin_deviceAlarm_edit'" @click="handleEdit(row)"> 处理 </el-button>
					</template>
				</el-table-column>
			</el-table>

			<!-- 分页组件 -->
			<pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />
		</div>

		<!-- 编辑、新增弹窗 -->
		<form-dialog ref="formDialogRef" @refresh="getDataList(false)" />

		<!-- 导入excel弹窗 (需要在 upms-biz/resources/file 下维护模板) -->
		<upload-excel
			ref="excelUploadRef"
			title="导入"
			url="/admin/deviceAlarm/import"
			temp-url="/admin/sys-file/local/file/deviceAlarm.xlsx"
			@refreshDataList="getDataList"
		/>

		<el-dialog title="报警处理" v-model="editModal" draggable>
			<el-form ref="formRef" :model="editForm" label-width="auto">
				<el-form-item label="设备sn" prop="deviceSn">
          {{ editForm.deviceSn }}
				</el-form-item>
        <el-form-item label="上报时间" prop="gpsTime">
          {{ editForm.gpsTime }}
        </el-form-item>
        <el-form-item label="报警状态" prop="alarmStatus">
          <el-select v-model="editForm.alarmStatus" placeholder="请选择报警状态">
            <el-option label="未处理" value="0"></el-option>
            <el-option label="已处理" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处理备注" prop="resolvedRemark">
          <el-input type="textarea" maxlength="150" rows="3" placeholder="请选择处理备注" v-model="editForm.resolvedRemark"></el-input>
        </el-form-item>
			</el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="editModal = false">取消</el-button>
					<el-button @click="submitEdit" type="primary">确定</el-button>
				</span>
      </template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemDeviceAlarm">
// ========== 导入声明 ==========
import { BasicTableProps, useTable } from '/@/hooks/table';
import { fetchList, delObjs, putObj } from '/@/api/admin/deviceAlarm';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { useDict } from '/@/hooks/dict';

// ========== 组件声明 ==========
// 异步加载表单弹窗组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));

// ========== 字典数据 ==========

// ========== 组件引用 ==========
const formDialogRef = ref(); // 表单弹窗引用
const excelUploadRef = ref(); // Excel上传弹窗引用
const queryRef = ref(); // 查询表单引用

// ========== 响应式数据 ==========
const showSearch = ref(true); // 是否显示搜索区域
const selectObjs = ref([]) as any; // 表格多选数据
const multiple = ref(true); // 是否多选

// ========== 表格状态 ==========
const state: BasicTableProps = reactive<BasicTableProps>({
	queryForm: {}, // 查询参数
	pageList: (query) => {
		return fetchList({
			...query,
			gpsTime: undefined,
			gpsTimeStart: query.gpsTime?.[0],
			gpsTimeEnd: query.gpsTime?.[1],
			resolvedTime: undefined,
			resolvedTimeStart: query.resolvedTime?.[0],
			resolvedTimeEnd: query.resolvedTime?.[1],
		});
	}, // 分页查询方法
});

// ========== Hook引用 ==========
// 表格相关Hook
const { getDataList, currentChangeHandle, sizeChangeHandle, sortChangeHandle, downBlobFile, tableStyle } = useTable(state);

// ========== 方法定义 ==========
/**
 * 重置查询条件
 */
const resetQuery = () => {
	// 清空搜索条件
	queryRef.value?.resetFields();
	// 清空多选
	selectObjs.value = [];
	// 重新查询
	getDataList();
};

/**
 * 导出Excel文件
 */
const exportExcel = () => {
	downBlobFile('/admin/deviceAlarm/export', Object.assign(state.queryForm, { ids: selectObjs }), 'deviceAlarm.xlsx');
};

/**
 * 表格多选事件处理
 * @param objs 选中的数据行
 */
const selectionChangHandle = (objs: { alarmId: string }[]) => {
	selectObjs.value = objs.map(({ alarmId }) => alarmId);
	multiple.value = !objs.length;
};

/**
 * 删除数据处理
 * @param ids 要删除的数据ID数组
 */
const handleDelete = async (ids: string[]) => {
	try {
		await useMessageBox().confirm('此操作将永久删除');
	} catch {
		return;
	}

	try {
		await delObjs(ids);
		getDataList();
		useMessage().success('删除成功');
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};

/*处理报警*/
const editModal = ref(false);
const editForm = ref<any>({});
const handleEdit = (row: any) => {
	editModal.value = true;
  editForm.value = { ...row };
};
const submitEdit = async () => {
  const res = await putObj(editForm.value);
  if (res.code === 0) {
    useMessage().success('操作成功');
    editModal.value = false;
    getDataList();
  } else {
    useMessage().error(res.msg);
  }
}
</script>
